/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.job.admin.controller;

import com.google.common.collect.Ordering;
import com.lvyh.lightframe.job.admin.annotation.PermitLimit;
import com.lvyh.lightframe.job.admin.bean.JobAlarmConfigBean;
import com.lvyh.lightframe.job.admin.bean.JobTaskDefBean;
import com.lvyh.lightframe.job.admin.manager.ScheduleServerManager;
import com.lvyh.lightframe.job.admin.route.ExecuteNodeRouteStrategy;
import com.lvyh.lightframe.job.admin.route.ExecuteNodeRouter;
import com.lvyh.lightframe.job.enums.AlarmStatus;
import com.lvyh.lightframe.job.enums.AlarmType;
import com.lvyh.lightframe.job.enums.ErrorCode;
import com.lvyh.lightframe.job.admin.util.DateUtils;
import com.lvyh.lightframe.job.common.Result;
import com.lvyh.lightframe.job.admin.model.JobTaskDefParam;
import com.lvyh.lightframe.job.admin.processor.JobManageProcessor;
import org.apache.commons.lang3.StringUtils;
import org.quartz.CronExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author lvyh 2021/04/11.
 */
@Controller
@RequestMapping("/task")
public class TaskController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(TaskController.class.getName());

    @Autowired
    private JobManageProcessor jobManageProcessor;

    @Autowired
    private ScheduleServerManager scheduleServerManager;

    @RequestMapping
    @PermitLimit(superAdmin = true)
    public String index(Model model) throws Exception {

        List<JobTaskDefBean> dataList = jobManageProcessor.getJobTaskDefList();
        dataList.sort(Ordering.natural().onResultOf(JobTaskDefBean::getDisplayName));

        dataList.forEach(p -> p.setCreateTimeText(DateUtils.format(p.getCreateTime())));
        dataList.forEach(p -> p.setUpdateTimeText(DateUtils.format(p.getUpdateTime())));
        model.addAttribute("dataList", dataList);

        return "task/index";
    }

    @RequestMapping("/save")
    @PermitLimit(superAdmin = true)
    @ResponseBody
    public Result<String> save(JobTaskDefParam param) throws Exception {

        Assert.notNull(param.getTaskName(), "Task name must not be empty.");
        Assert.notNull(param.getTaskType(), "Task type must not be empty.");
        Assert.notNull(param.getCronExp(), "Cron expression must not be empty.");

        try {
            new CronExpression(param.getCronExp());
        } catch (ParseException e) {
            logger.error("Cron expression format error, cron={},error=", param.getCronExp(), e);
            throw new RuntimeException("Cron expression format error,", e);
        }

        JobTaskDefBean existEnv = jobManageProcessor.getJobTaskDefInfo(param.getTaskType(), param.getTaskName());
        if (existEnv != null) {
            return Result.create(ErrorCode.FAILED, "Task already exists and cannot be added repeatedly");
        }

        JobTaskDefBean taskDefBean = new JobTaskDefBean();
        BeanUtils.copyProperties(param, taskDefBean);
        taskDefBean.setDisplayName(param.getTaskName());
        taskDefBean.setCreator(this.getLoginName());
        taskDefBean.setOwner(this.getLoginName());
        taskDefBean.setVersionId(System.currentTimeMillis());
        taskDefBean.setExecutorFailRetryCount(param.getRetryNum() != null ? param.getRetryNum() : 1);
        taskDefBean.setExecutorTimeout(param.getTimeout() != null ? param.getTimeout() : 30 * 1000);
        taskDefBean.setStartTime(param.getStartTime() != null ? DateUtils.parseDate(param.getStartTime()) : new Date());
        taskDefBean.setEndTime(param.getEndTime() != null ? DateUtils.parseDate(param.getEndTime()) : DateUtils.addDays(new Date(), 10 * 365));

        int taskId = jobManageProcessor.saveJobTaskDefBean(taskDefBean);

        JobAlarmConfigBean alarmConfigBean = new JobAlarmConfigBean();
        long smsInterval = 24 * 60 * 60 * 1000; // 毫秒
        long emailInterval = 24 * 60 * 60 * 1000;

        alarmConfigBean.setEmailIntervalTime(String.valueOf(emailInterval));
        alarmConfigBean.setSmsIntervalTime(String.valueOf(smsInterval));

        BeanUtils.copyProperties(param, alarmConfigBean);
        alarmConfigBean.setSmsLastSendTime("0");
        alarmConfigBean.setEmailLastSendTime("0");
        alarmConfigBean.setAlarmName("");
        alarmConfigBean.setStatus(AlarmStatus.ENABLED.getStatus());
        alarmConfigBean.setAlarmType(AlarmType.TASK.getKey());
        alarmConfigBean.setObjectId(taskId);

        jobManageProcessor.saveJobAlarmConfigBean(alarmConfigBean);
        return Result.SUCCESS();
    }


    @RequestMapping("/update")
    @PermitLimit(superAdmin = true)
    @ResponseBody
    public Result<String> update(JobTaskDefParam param) throws Exception {

        Assert.notNull(param.getTaskName(), "Task name must not be empty.");
        Assert.notNull(param.getTaskType(), "Task type must not be empty.");

        JobTaskDefBean existData = jobManageProcessor.getJobTaskDefInfo(param.getTaskType(), param.getTaskName());
        if (existData == null) {
            return Result.create(ErrorCode.FAILED, "Task must not be null");
        }

        JobAlarmConfigBean alarmConfigBean = jobManageProcessor.getJobAlarmConfigInfo(existData.getId());
        if (alarmConfigBean == null) {
            alarmConfigBean = new JobAlarmConfigBean();
            long smsInterval = 24 * 60 * 60 * 1000; // 毫秒
            long emailInterval = 24 * 60 * 60 * 1000;

            alarmConfigBean.setEmailIntervalTime(String.valueOf(emailInterval));
            alarmConfigBean.setSmsIntervalTime(String.valueOf(smsInterval));

            BeanUtils.copyProperties(param, alarmConfigBean);
            alarmConfigBean.setSmsLastSendTime("0");
            alarmConfigBean.setEmailLastSendTime("0");
            alarmConfigBean.setAlarmName("");
            alarmConfigBean.setStatus(AlarmStatus.ENABLED.getStatus());
            alarmConfigBean.setAlarmType(AlarmType.TASK.getKey());
            alarmConfigBean.setObjectId(existData.getId());

            jobManageProcessor.saveJobAlarmConfigBean(alarmConfigBean);
        }

        BeanUtils.copyProperties(param, existData);

        boolean result = jobManageProcessor.updateJobTaskDefBean(existData);
        return (result) ? Result.SUCCESS() : Result.FAILED();
    }


    @RequestMapping("/remove")
    @PermitLimit(superAdmin = true)
    @ResponseBody
    public Result<String> remove(String taskName, Integer taskType) throws Exception {

        Assert.notNull(taskName, "Task name must not be empty.");
        Assert.notNull(taskType, "Task type must not be empty.");

        boolean result = jobManageProcessor.deleteJobTaskDefBean(taskType, taskName);
        return (result) ? Result.SUCCESS() : Result.FAILED();
    }

    @RequestMapping("/immediately-exec")
    @PermitLimit(superAdmin = true)
    @ResponseBody
    public Result<String> immediatelyExec(String taskName, Integer taskType) throws Exception {

        Assert.notNull(taskName, "Task name must not be empty.");
        Assert.notNull(taskType, "Task type must not be empty.");

        JobTaskDefBean existData = jobManageProcessor.getJobTaskDefInfo(taskType, taskName);
        if (existData == null) {
            return Result.create(ErrorCode.FAILED, "Task info must not be null");
        }

        String scheduleNode = "";
        if (!StringUtils.isEmpty(existData.getScheduleNode())) {
            scheduleNode = existData.getScheduleNode();
        } else {
            Set<String> onlineServerNodes = scheduleServerManager.getCurrentServerNodes();
            if (CollectionUtils.isEmpty(onlineServerNodes)) {
                return Result.create(ErrorCode.FAILED, "Server node must not be null");
            }
            List<String> addressList = new ArrayList<>(onlineServerNodes);
            ExecuteNodeRouter executeNodeRouter = ExecuteNodeRouteStrategy.convert(existData.getExecutorRouteStrategy()).getRouter();
            Result<String> nodeRouterResult = executeNodeRouter.route(existData.getId(), addressList);
            String address = nodeRouterResult.getResult();
            scheduleNode = address;
        }

        scheduleServerManager.addTmpTaskNode(existData.getId(), scheduleNode);
        return Result.SUCCESS();
    }


}
